package com.huahua.graduateschoolspringboot.entity;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.huahua.graduateschoolspringboot.enums.ErrorCodeEnum;
import lombok.Data;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @author LoveHuahua
 * @date 2021年09月07日 14:39
 * @description believe in yourself
 */
@Data
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private int code;

    private String message;

    private Long total;

    private T data;

    public static <T> R<T> success() {
        return success(200, null);
    }

    public static <T> R<List<T>> emptyList() {
        return success(200, Lists.newArrayList());
    }


    public static <T> R<T> success(T t) {
        return success(200, t);
    }


    public static <T> R<T> success(Integer code, T t) {
        return success(code, "操作成功", t);
    }


    public static <T> R<List<T>> successPage(IPage<T> t) {
        return successPage(200, t);
    }

    public static <T> R<List<T>> successPage(Integer code, IPage<T> t) {
        return successPage(code, "操作成功", t);
    }

    public static <T> R<List<T>> successPage(Integer code, String message, IPage<T> t) {
        R<List<T>> objectR = new R<>();
        objectR.setMessage(message);
        objectR.setCode(code);
        objectR.setTotal(t.getTotal());
        objectR.setData(t.getRecords());
        return objectR;
    }

    public static <T> R<T> success(Integer code, String message, T t) {
        R<T> objectR = new R<>();
        objectR.setMessage(message);
        objectR.setCode(code);
        if (t instanceof Collection) {
            objectR.setTotal((long) ((Collection<?>) t).size());
        }
        objectR.setData(t);
        return objectR;
    }

    public static <T> R<T> fail() {
        R<T> objectR = new R<>();
        objectR.setMessage("操作失败");
        objectR.setCode(500);
        return objectR;
    }


    public static <T> R<T> fail(String message) {
        R<T> objectR = new R<>();
        objectR.setMessage(message);
        objectR.setCode(500);
        return objectR;
    }

    public static <T> R<T> fail(ErrorCodeEnum errorCodeEnum) {
        R<T> objectR = new R<>();
        objectR.setMessage(errorCodeEnum.getMessage());
        objectR.setCode(errorCodeEnum.getCode());
        return objectR;
    }

    public static <T> R<T> fail(Integer code, String message) {
        R<T> objectR = new R<>();
        objectR.setMessage(message);
        objectR.setCode(code);
        return objectR;
    }

}
